define([
    'app',
    'css!css/core/login'
], function(app) {
    app.controller('LoginController', ['$location', 'Config', 'Dialog', 'AuthFactory', 'AuthService', 'KaptchaProvider',
        function($location, Config, Dialog, AuthFactory, AuthService, KaptchaProvider) {
        var self = this;

        self.user = {
            name: '',
            password: '',
            kaptcha: ''
        };

        self.kaptcha = KaptchaProvider.load();
        self.changeKaptcha = function() {
            self.kaptcha = KaptchaProvider.refresh();
        };

        self.login = function(valid) {
            if (valid) {
                AuthService.login(self.user).then(function(resp) {
                    if (resp.success) {
                        var defaultTargetUrl = AuthFactory.getParameters().target;
                        if (defaultTargetUrl == '') {
                            defaultTargetUrl = $location.absUrl().replace(/(\?reload)?#\/.*$/, '#' + Config.defaultPath);
                        }
                        AuthFactory.setParameters({
                            user: self.user.name,
                            logout: false,
                            target: '',
                            authenticated: true
                        });
                        location.href = defaultTargetUrl;
                    } else {
                        self.changeKaptcha();
                    }
                });
            }
        }
    }]);
});
